﻿using System.Collections;
using System.Threading;
using System;
using System.Windows.Threading;

namespace NS_Client
{
    /// <summary>Delegate function representing method to handle MessageChanged</summary>
    public delegate void MessageChangedHandler(object sender, object args);

    /// <summary>Provides accessibility for multiple threads to call-back to parent thread</summary>
    public class ResponseHandler
    {
        /// <summary>The parent thread's Dispatcher other threads will invoke upon</summary>
        private Dispatcher parent;

        /// <summary>Occurs when a response is Handled</summary>
        public event MessageChangedHandler MessageChanged;

        /// <summary>Default constructor of ResponseHandler</summary>
        /// <param name="ParentDispatcher">The parent threads Dispatcher all child threads will invoke delegate upon</param>
        public ResponseHandler(Dispatcher ParentDispatcher)
        {
            parent = ParentDispatcher;
        }

        /// <summary>Invokes the MessageChangedHandler delegate on the parent thread's Dispatcher</summary>
        public void HandleResponse(object reply)
        {
            // Invoke the MessageChanged delegate handler on the Parent thread that created this ResponseHandler
            parent.BeginInvoke((Action)delegate { MessageChanged(this, reply); }, DispatcherPriority.Send);
        }      
    }
}
